<!doctype html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="Keywords" content="">
	<meta name="Description" content="">
	<title>0616-JS作业-拖拽盒子-螺旋</title>
	<style type="text/css">
		html{font-family: "Microsoft YaHei";}
		body{
			margin: 0;
			cursor: default;
			-webkit-user-select:none;
			-moz-user-select:none;
			-ms-user-select:none;
			user-select:none;
		}
		.box{
			position: absolute;
			left: 50%;
			top: 50%;
			width: 100px;
			height: 100px;
			margin: -50px;
			padding: 20px 0;
			background-color: #006eff;
			font-size: 16px;
			line-height: 30px;
			color: #fff;
			text-align: center;
			box-sizing: border-box;
		}
		.box i{
			color: #ffc700;
			font-weight: 700;
			font-style: normal;
		}
	</style>
</head>
<body>
	<div class="box"></div>
</body>
<script>
	var oBox = document.getElementsByClassName('box')[0],
		aText = ['已锁定<br>双击<i>解锁</i>','按住拖动<br>双击<i>锁定</i>'],
        bW,bH,mX,mY,
		oSw1 = false,//鼠标按住开关
		oSw2 = true;//双击开关

	//获取浏览器窗口大小 当浏览器窗口大小发生改变时重新获取
    fnWH();
    window.onresize = function(){
        fnWH();
    };
    
    //注册事件监听 改变文本
    fnAddEL();

    //第一次双击盒子时移除事件监听 再次双击恢复
    oBox.addEventListener('dblclick',function(){
        if(oSw2){
            oBox.removeEventListener('mousedown',fnOn,false);
            oBox.removeEventListener('mouseup',fnOff,false);
            oBox.style.cursor = 'default';
            oBox.innerHTML = aText[0];
            oSw2 = false;
        }else{
            fnAddEL();
            oSw2 = true;
	    }
    },false);

    document.onmousemove = function(ev){
        var ev = ev || window.event;
        mX = ev.clientX;
        mY = ev.clientY;
        if(oSw1){//判断是否鼠标按下
            if(mX > 50){//防止出界
                oBox.style.left = mX+'px';
            }else{
                oBox.style.left = 50+'px';
            }
            if(mX > bW-50){
                oBox.style.left = bW-50+'px';
            }
            
            if(mY > 50){
                oBox.style.top = mY+'px';
            }else{
                oBox.style.top = 50+'px';
            }
            if(mY > bH-50){
                oBox.style.top = bH-50+'px';
            }
        }
    };
    
    //获取浏览器窗口大小
    function fnWH(){
        bW = document.documentElement.clientWidth;
        bH = document.documentElement.clientHeight;
    }
    //注册事件监听 同时改变文本
    function fnAddEL(){
        oBox.addEventListener('mousedown',fnOn,false);
        oBox.addEventListener('mouseup',fnOff,false);
        oBox.style.cursor = 'move';
        oBox.innerHTML = aText[1];
    }
    function fnOn(){
        oSw1 = true;
    }
    function fnOff(){
        oSw1 = false;
    }
</script>
</html>